package com.hexseek.libretvcloud.service;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hexseek.libretvcloud.mapper.ProxyMapper;
import com.hexseek.libretvcloud.model.Proxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhougb9
 * @version 1.0.0
 * @description TODO
 * @date 2025/5/14 18:19
 * @title CustomProxyService
 */
@Service
public class ProxyService {

    @Autowired
    private ProxyMapper proxyMapper;

    public List<Proxy> getDefaultProxy() {
        return proxyMapper.selectDefaultProxy();
    }

    public List<Proxy> getCustomProxy(String userId) {

        return proxyMapper.selectCustomProxyByUserId(userId);

    }

    // 添加新的自定义API源
    public void addCustomProxy(String userId, String name, String apiUrl,
                                          String detailUrl, boolean adult) {

        Proxy source = new Proxy();
        source.setUserId(userId);
        source.setName(name);
        source.setApiUrl(apiUrl);
        source.setDetailUrl(detailUrl);
        source.setAdult(adult);
        source.setEnabled(true);
        proxyMapper.insert(source);
    }

    // 更新自定义API源
    public void updateCustomProxy(Long id, String userId, String name,
                                             String apiUrl, String detailUrl, boolean adult) {
        Proxy source = proxyMapper.selectById(id);
        if (source == null) {
            throw new IllegalArgumentException("找不到API源: " + id);
        }

        if (!source.getUserId().equals(userId)) {
            throw new IllegalArgumentException("无权修改此API源");
        }

        LambdaUpdateWrapper<Proxy> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper
                .set(Proxy::getName, name)
                .set(Proxy::getApiUrl, apiUrl)
                .set(Proxy::getDetailUrl, detailUrl)
                .set(Proxy::getAdult, adult)
                .set(Proxy::getUpdateTime, System.currentTimeMillis());

        proxyMapper.update(null, updateWrapper);
    }

    // 删除自定义API源
    public void deleteCustomProxy(Long id, String userId) {
        Proxy source = proxyMapper.selectById(id);
        if (source == null) {
            throw new IllegalArgumentException("找不到API源: " + id);
        }

        if (!source.getUserId().equals(userId)) {
            throw new IllegalArgumentException("无权删除此API源");
        }

        // 执行删除
        int rows = proxyMapper.deleteById(id);
        if (rows == 0) {
            throw new IllegalArgumentException("删除失败，API源可能已不存在");
        }
    }
}